/**
 * 您可以将常用的方法、或系统 API，统一封装，暴露全局，以便各页面、组件调用，而无需 require / import.
 */
import prompt from '@system.prompt';
import file from '@system.file';
import texttoaudio from '@service.texttoaudio'

import { Buffer } from 'buffer';

export function tts(content) {
  texttoaudio.speak({
    lang: 'zh_CN',
    content: content,
    pitch: 1,
    rate: 1,
    success: (data) => {
      console.log(`handling success`)
    },
    fail: (data, code) => {
      console.log(`handling fail, code = ${code}`)
    }
  })
}

export function arrayBufferToBase64(arrayBuffer) {
  const base64Data = Buffer.from(arrayBuffer).toString("base64");
  return base64Data;
}

export function readArrayBufferFromUri(uri) {
  return new Promise((resolve, reject) => {
    file.readArrayBuffer({
      uri: uri,
      success: (data) => resolve(data.buffer),
      fail: reject
    })
  })
}
 export function queryString(url, query) {
   let str = [];
   for (let key in query) {
     str.push(key + '=' + query[key]);
   }
   let paramStr = str.join('&');
   return paramStr ? `${url}?${paramStr}` : url;
 }
 
 export function showToast(message = '', duration = 0) {
   if (!message) return;
   prompt.showToast({
     message: message,
     duration
   });
 }

 export function genUniqueId() {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 15);
  return `${timestamp}-${random}`;
}

export function getRegPhotoText(responseJson) {
  // return responseJson.data.msg.choices[0].message.content;
  return responseJson.data.msg
}

export function getRegAudioText(responseJson) {
  //return responseJson.output.choices[0].message.content[0].text;
  return responseJson.data.msg.choices[0].message.content;
}

export function getTTSReuqestData(voice_type, text) {
    // 创建对象
  const data = {
    "app": {
        "appid": "6836664715",
        "token": "BSLwS1a7bUXc34bUW55eMeA7hRisTi7D",
        "cluster": "volcano_tts"
    },
    "user": {
        "uid": genUniqueId()
    },
    "audio": {
        "voice_type": voice_type,
        "encoding": "mp3",
        "speed_ratio": 1.0
    },
    "request": {
        "reqid": "uuid",
        "text": text,
        "operation": "query"
    }
  };

  // 将对象转换为 JSON 字符串
  const jsonString = JSON.stringify(data, null, 2);

  // 输出 JSON 字符串
  console.log(jsonString);
  return jsonString
}

export function base64ToUint8Array(base64) {
  // 去除 Base64 字符串中的数据头
  // const base64Data = base64.replace(/^data:audio\/\w+;base64,/, '');
  // 使用 Buffer 将 Base64 字符串解码
  const buffer = Buffer.from(base64, 'base64');
  // 将 Buffer 转换为 Uint8Array
  return new Uint8Array(buffer);
}

export function writeBase64ToAudioFile(base64, filePath, callback) {
  try {
    const uint8Array = base64ToUint8Array(base64);
    console.log('buffer')
    console.log(uint8Array)
    file.writeArrayBuffer({
      uri: filePath,
      buffer: uint8Array,
      success: function () {
        console.log('文件写入成功');
              callback('success')
      },
      fail: function (data, code) {
        console.log(`文件写入失败，错误码: ${code}，错误信息: ${data}`);
              callback('fail')
      }
    })
  } catch(error) {
    console.log(`writeBase64ToAudioFile异常，error: ${error}`);
    showToast('语音合成异常，请重试或者关闭趣味音效')
  }
}

export function getVoiceTrainReuqestData(speakerId, audioBase64) {
  console.log('invoke getVoiceTrainReuqestData')
  console.log('audioBase64' + audioBase64)
  // 创建对象
  const data = {
    "speaker_id": speakerId,
    "appid": "6836664715",
    "audios": [{
            "audio_bytes": audioBase64,
            "audio_format": "aac"
    }],
    "source": 2,
    "language": 0,
    "model_type": 1
  };
  // 将对象转换为 JSON 字符串
  const jsonString = JSON.stringify(data, null, 2);
  // 输出 JSON 字符串
  console.log(jsonString);
  return jsonString
}

export function getAIGCReuqestData(text) {
  const data = {
    "req_key": "high_aes_general_v21_L",
    "prompt": text,
    "model_version": "general_v2.1_L",
    "req_schedule_conf": "general_v20_9B_pe",
    "llm_seed": -1,
    "seed": -1,
    "scale": 8.5,
    "ddim_steps": 25,
    "width": 512,
    "height": 512,
    "use_pre_llm": false,
    "use_sr": false,
    "sr_seed": -1,
    "sr_strength": 0.4,
    "sr_scale": 3.5,
    "sr_steps": 20,
    "is_only_sr": false,
    "return_url": true,
    "logo_info": {
        "add_logo": true,
        "position": 0,
        "language": 0,
        "opacity": 0.1,
        "logo_text_content": "vivo蓝河操作系统创新赛"
    }
  };

  // 将对象转换为 JSON 字符串
  const jsonString = JSON.stringify(data, null, 2);

  // 输出 JSON 字符串
  console.log(jsonString);
  return jsonString
}

function padWithZero(num) {
  if (num < 10) {
      return '0' + num;
  }
  return '' + num;
}





